package com.hnhcyy.goods.service.impl;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hnhcyy.b2b.common.util.JsonUtils;
import com.hnhcyy.b2b.common.util.LogUtil;
import com.hnhcyy.goods.mapper.SpBalMapper;
import com.hnhcyy.goods.pojo.SpBal;
import com.hnhcyy.goods.service.SpBalService;

@Service
public class SpBalServiceImpl implements SpBalService{
	
	private Logger logger = LoggerFactory.getLogger(SpBalServiceImpl.class);
	
	@Autowired
	private SpBalMapper spBalMapper;
	
	@Value("${spbal.update.logs.path}")
	private String path;

	@Override
	public int updateOrInsertBatch(List<SpBal> spbalList) {
		if(spbalList == null) {
			return 0;
		}
		long starttime = System.currentTimeMillis();
		int affect = 0;
		for(int i = 0, size = spbalList.size(); i < size; i++) {
			SpBal spbal = spbalList.get(i);
			String spid = spbal.getSpid();
			try {
				// 查询商品库存是否有记录
//				SpBal oldSpbal = spBalMapper.selectItemById(spid);
				int count = spBalMapper.selectCountById(spid);
				//执行新增或更新操作
				if(count > 0) {// 库存表有数据，只需更新即可
					affect += spBalMapper.updateItem(spbal);
				}else {// 新增
					affect += spBalMapper.insertItem(spbal);
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("{}更新失败", spid);
				try {
					LogUtil.writeErorToTxt(path, JsonUtils.objectToJson(spbal));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			/*try {
				//休眠100ms
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}*/
		}
		long endtime = System.currentTimeMillis();
		logger.info("更新库存耗时：{}秒" , (endtime - starttime)/1000.0);
		return affect;
	}

	@Transactional
	@Override
	public int updateFast(List<SpBal> spBalList) {
		long start = System.currentTimeMillis();
		/*// 清空临时表
		spBalMapper.truncateSpBalTmp();
		// 批量插入数据
		int i = spBalMapper.insertTmpByBatch(spBalList);*/
		int i = spBalMapper.replaceByBatch(spBalList);
		long end = System.currentTimeMillis();
		System.out.println("======更新库存表耗时======" + (end - start) / 1000.0 + "秒");
		return i;
	}

}
